/**
 * Copyright (c) 2012-2013 Yunzhisheng(Shanghai) Co.Ltd. All right reserved.
 * @FileName : WindowService.java
 * @ProjectName : letvAssistant
 * @PakageName : cn.yunzhisheng.voicetv
 * @Author : Brant
 * @CreateDate : 2013-5-13
 */
package cn.yunzhisheng.vui.assistant.tv;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.view.KeyEvent;
import android.widget.Toast;
import cn.yunzhisheng.common.util.LogUtil;
import cn.yunzhisheng.vui.assistant.tv.session.SessionManager;
import cn.yunzhisheng.vui.assistant.tv.session.SessionManager.ISessionManagerListener;
import cn.yunzhisheng.vui.assistant.tv.IVuiVoiceCallBack;
import cn.yunzhisheng.vui.assistant.util.PackageUtil;

/**
 * @Module : 隶属模块名
 * @Comments : 描述
 * @Author : Brant
 * @CreateDate : 2013-5-13
 * @ModifiedBy : Brant
 * @ModifiedDate: 2013-5-13
 * @Modified: 2013-5-13: 实现基本功能
 */
public class WindowService extends Service implements OnKeyListener, OnDismissListener {
    private static final String TAG = "WindowService";
    private static final int AUTO_FINISH_DELAY = 10000;

    public static final String MSG_VIRTUAL_KEY_BACK = "MSG_VIRTUAL_KEY_BACK";
    public static final String MSG_VIRTUAL_KEY_CENTER = "MSG_VIRTUAL_KEY_ENTER";
    public static final String MSG_VIRTUAL_KEY_LEFT = "MSG_VIRTUAL_KEY_LEFT";
    public static final String MSG_VIRTUAL_KEY_RIGHT = "MSG_VIRTUAL_KEY_RIGHT";
    public static final String MSG_VIRTUAL_KEY_UP = "MSG_VIRTUAL_KEY_UP";
    public static final String MSG_VIRTUAL_KEY_DOWN = "MSG_VIRTUAL_KEY_DOWN";
    public static final String MSG_VIRTUAL_KEY_HOME = "MSG_VIRTUAL_KEY_HOME";
    public static final String MSG_VIRTUAL_KEY_MENU = "MSG_VIRTUAL_KEY_MENU";

    public static final String PROTOCAL_CUSTOMER_DATA = "PROTOCAL_CUSTOMER_DATA";

    public static final String BUNDLE_DATA_FROM_MOBILE_CONTROL = "BUNDLE_DATA_FROM_MOBILE_CONTROL";

    private final static int MSG_VOICE_BUTTON_START = 0x1;
    private final static int MSG_VOICE_BUTTON_STOP = 0x2;
    private final static int MSG_AUTO_FINISH = 0x3;

    private final static int ADD_FLOAT_WINDOW = 5;
    private final static int REMOVE_FLOAT_WINDOW = 6;

    private Timer mTimer;
    // private ViewFlipper mViewFlipper;
    private List<String> mLauncherPackage;
    // private View mFloatView = null;
    private boolean floatWindowIsShowing = false;

    private SessionManager mSessionManager = null;

    private boolean misConnectClient = false;

    private ISessionManagerListener mSessionManagerListener = new ISessionManagerListener() {

        @Override
        public void onConnectivityChanged(boolean hasNetwork) {
            updateNetWorkStatus(hasNetwork);
        }

        @Override
        public void onResetTimer() {
            LogUtil.w(TAG, "onResetTimer");
            resetTimer();
        }

        @Override
        public void onCancelTimer() {
            LogUtil.w(TAG, "onCancelTimer");
            cancelTimer();
        }

        @Override
        public void onConnectClient() {
            Toast.makeText(WindowService.this, "手机遥控器已连接", Toast.LENGTH_SHORT).show();
            misConnectClient = true;
        }

        @Override
        public void onDisconnectClient() {
            misConnectClient = false;
        }

        // @Override
        // public void onMusicSearchDone(PlayList playList) {
        //
        // }
    };

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            LogUtil.w(TAG, intent.toString());
            String action = intent.getAction();
            if (MSG_VIRTUAL_KEY_BACK.equals(action)) {
                if (!mSessionManager.getPopupWindowIsShowing()) {
                    onKey(null, KeyEvent.KEYCODE_BACK, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
                    onKey(null, KeyEvent.KEYCODE_BACK, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
                } else {
                    mSessionManager.hidePopup();
                }
            } else if (MSG_VIRTUAL_KEY_CENTER.equals(action)) {
                if (!mSessionManager.getPopupWindowIsShowing()) {
                    onKey(null, KeyEvent.KEYCODE_DPAD_CENTER, new KeyEvent(KeyEvent.ACTION_DOWN,
                            KeyEvent.KEYCODE_DPAD_CENTER));
                    onKey(null, KeyEvent.KEYCODE_DPAD_CENTER, new KeyEvent(KeyEvent.ACTION_UP,
                            KeyEvent.KEYCODE_DPAD_CENTER));

                }
            } else if (MSG_VIRTUAL_KEY_LEFT.equals(action)) {
                if (!mSessionManager.getPopupWindowIsShowing()) {
                    onKey(null, KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(KeyEvent.ACTION_DOWN,
                            KeyEvent.KEYCODE_DPAD_LEFT));
                    onKey(null, KeyEvent.KEYCODE_DPAD_LEFT,
                            new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT));
                }
            } else if (MSG_VIRTUAL_KEY_RIGHT.equals(action)) {
                if (!mSessionManager.getPopupWindowIsShowing()) {
                    onKey(null, KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_DOWN,
                            KeyEvent.KEYCODE_DPAD_RIGHT));
                    onKey(null, KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(KeyEvent.ACTION_UP,
                            KeyEvent.KEYCODE_DPAD_RIGHT));
                }
            } else if (MSG_VIRTUAL_KEY_UP.equals(action)) {
                if (!mSessionManager.getPopupWindowIsShowing()) {
                    onKey(null, KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP));
                    onKey(null, KeyEvent.KEYCODE_DPAD_UP, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_UP));

                }
            } else if (MSG_VIRTUAL_KEY_DOWN.equals(action)) {
                if (!mSessionManager.getPopupWindowIsShowing()) {
                    onKey(null, KeyEvent.KEYCODE_DPAD_DOWN, new KeyEvent(KeyEvent.ACTION_DOWN,
                            KeyEvent.KEYCODE_DPAD_DOWN));
                    onKey(null, KeyEvent.KEYCODE_DPAD_DOWN,
                            new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_DOWN));
                }
            }
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int action = msg.what;
            switch (action) {
            case MSG_VOICE_BUTTON_START:
                mSessionManager.startByControlButton();
                // show();
                break;
            case MSG_VOICE_BUTTON_STOP:
                resetTimer();
                mSessionManager.stopByControlButton();
                break;
            case MSG_AUTO_FINISH:
                LogUtil.w(TAG, "Auto stop service time out!");
                // stopSelf();
                break;
            case ADD_FLOAT_WINDOW:
                break;
            case REMOVE_FLOAT_WINDOW:
                break;
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private final IVoiceService.Stub mBinder = new IVoiceService.Stub() {

        @Override
        public void setVoiceMessageCallback(IVuiVoiceCallBack ck) throws RemoteException {
            if (mSessionManager != null) mSessionManager.setVoiceMessageCallback(ck);
        }

        @Override
        public boolean hasConnectClient() throws RemoteException {
            return misConnectClient;
        }
    };

    @Override
    public void onCreate() {
        LogUtil.w(TAG, "onCreate");
        super.onCreate();
        mLauncherPackage = PackageUtil.getLauncherPackages(this);
        mSessionManager = new SessionManager(this, null);
        mSessionManager.setSessionListener(mSessionManagerListener);
        registReceiver();
        mSessionManager.onResume();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (mTimer == null) {
            mTimer = new Timer();
            mTimer.scheduleAtFixedRate(new RefreshTask(), 1000, 500);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    public void show() {
        resetTimer();
    }

    public void hide() {
        resetTimer();
    }

    public void dismiss() {
        LogUtil.w(TAG, "dismiss");
        cancelTimer();
    }

    public void runOnThread(Runnable r) {
        if (r != null) {
            mHandler.post(r);
        }
    }

    private void registReceiver() {
        // IntentFilter filter = new IntentFilter();
        // filter.addAction(MSG_VIRTUAL_KEY_BACK);
        // filter.addAction(MSG_VIRTUAL_KEY_CENTER);
        // filter.addAction(MSG_VIRTUAL_KEY_LEFT);
        // filter.addAction(MSG_VIRTUAL_KEY_RIGHT);
        // filter.addAction(MSG_VIRTUAL_KEY_UP);
        // filter.addAction(MSG_VIRTUAL_KEY_DOWN);
        // registerReceiver(mBroadcastReceiver, filter);
    }

    private void unregistReceiver() {
        try {
            unregisterReceiver(mBroadcastReceiver);
        } catch (Exception e) {
            LogUtil.printStackTrace(e);
        }
    }

    private void cancelTimer() {
        LogUtil.w(TAG, "cancelTimer");
        mHandler.removeMessages(MSG_AUTO_FINISH);
    }

    private void resetTimer() {
        LogUtil.w(TAG, "resetTimer");
        cancelTimer();
        mHandler.sendEmptyMessageDelayed(MSG_AUTO_FINISH, AUTO_FINISH_DELAY);
    }

    private void updateNetWorkStatus(boolean hasNetwork) {
        LogUtil.w(TAG, "updateNetWorkStatus:hasNetwork " + hasNetwork);
        // if (hasNetwork) {
        // mViewNetWorkStatus.setVisibility(View.GONE);
        // } else {
        // mViewNetWorkStatus.setVisibility(View.VISIBLE);
        // // mTextViewNetWorkChangeContent.setText("当前网络连接异常，部分功能将无法使用~");
        // }
    }

    @SuppressLint("NewApi")
    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
    }

    private class RefreshTask extends TimerTask {

        @Override
        public void run() {
            if (PackageUtil.isHome(WindowService.this, mLauncherPackage) && !floatWindowIsShowing) {
                mHandler.sendEmptyMessage(ADD_FLOAT_WINDOW);
            } else if (!PackageUtil.isHome(WindowService.this, mLauncherPackage) && floatWindowIsShowing) {
                mHandler.sendEmptyMessage(REMOVE_FLOAT_WINDOW);
            }

        }

    }

    @Override
    public void onDestroy() {
        LogUtil.w(TAG, "onDestroy");
        super.onDestroy();
        mSessionManager.onPause();
        unregistReceiver();
        mSessionManagerListener = null;
        mSessionManager.onDestroy();
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        mHandler.removeMessages(MSG_VOICE_BUTTON_START);
        mHandler.removeMessages(MSG_VOICE_BUTTON_STOP);
        mHandler.removeMessages(MSG_AUTO_FINISH);
        mHandler.removeMessages(ADD_FLOAT_WINDOW);
        mHandler.removeMessages(REMOVE_FLOAT_WINDOW);
        mHandler = null;
    }

}
